package com.nerins.udp.server;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class RBACRequestDecoder extends CumulativeProtocolDecoder {

	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {

		int intSize = Integer.SIZE / 8;
		
		int requestType;
		int requestVersion;
		int requestIdLen;
		String requestId;
		int paramsLen;
		String params;
		
		if (in.remaining() >= intSize) {
			requestType = in.getInt();
		}else return false;

		if (in.remaining() >= intSize) {
			requestVersion = in.getInt();
		}else return false;
		
		if (in.remaining() >= intSize) {
			requestIdLen = in.getInt();
		}else return false;
		
		if (in.remaining() >= requestIdLen) {
			byte[] buf = new byte[requestIdLen];
			in.get(buf);
			requestId = new String(buf, "ISO-8859-1");
		}else return false;
			
		if (in.remaining() >= intSize) {
			paramsLen = in.getInt();
		}else return false;

		if (in.remaining() == paramsLen) {
				byte[] buf = new byte[paramsLen];
				in.get(buf);
				params = new String(buf, "ISO-8859-1");
		}else return false;

		RBACRequest request = new RBACRequest(requestType, requestVersion,
				requestId, params);

		out.write(request);

		return true;
	}
}